﻿using UnityEditor;
using System.Collections;
using System.IO;
using System.Text.RegularExpressions;
using System.Text;
using UnityEngine;
using System;

public class FbxAnimListPostprocessor : AssetPostprocessor
{
    public void OnPreprocessModel()
    {
        if (DragAndDrop.paths.Length <= 0)
            return;
        if (Directory.Exists(DragAndDrop.paths[0]))
        {
            foreach (var path in DragAndDrop.paths)
            {
                var result = GetPath(new DirectoryInfo(path));
                if (string.IsNullOrEmpty(result))
                    continue;
                CreateClip(result);
            }
        }
        else
        {
            CreateClip(DragAndDrop.paths[0]);
        }

        string GetPath(DirectoryInfo info)
        {
            var index = assetPath.IndexOf(info.Name);
            if (index == -1)
                return string.Empty;
            return info.FullName + assetPath.Substring(index + info.Name.Length).Replace("/", "\\");
        }
    }



    void CreateClip(string filePath)
    {
        if (Path.GetExtension(assetPath).ToLower() == ".fbx"
            && !assetPath.Contains("@"))
        {
            try
            {
                var sAnimList = ModelNameTxt(filePath);
                if (string.IsNullOrEmpty(sAnimList))
                {
                    sAnimList = ConfigureTxt(filePath);
                    if (string.IsNullOrEmpty(sAnimList))
                    {
                        return;
                    }
                }
                System.Collections.ArrayList List = new ArrayList();
                ParseAnimFile(sAnimList, ref List);

                ModelImporter modelImporter = assetImporter as ModelImporter;
                modelImporter.materialLocation = ModelImporterMaterialLocation.External;
                modelImporter.clipAnimations = (ModelImporterClipAnimation[])
                    List.ToArray(typeof(ModelImporterClipAnimation));
            }
            catch (Exception ex)
            {
                Debug.LogError(ex);
            }
        }
    }

    string ModelNameTxt(string filePath)
    {
        var fileName = Path.GetFileName(assetPath);
        var dir = Path.GetDirectoryName(filePath);
        var path = Path.ChangeExtension(Path.Combine(dir, fileName), ".txt");
        if (!File.Exists(path))
        {
            return string.Empty;
        }
        return File.ReadAllText(path);
    }

    string ConfigureTxt(string filePath)
    {
        var path = Path.GetDirectoryName(filePath) + @"\configure.txt";
        if (!File.Exists(path))
            return string.Empty;
        return AnimList(path, Path.GetFileNameWithoutExtension(assetPath));
    }

    string AnimList(string path, string target)
    {
        var lines = File.ReadAllLines(path);
        StringBuilder builder = null;
        foreach (var line in lines)
        {
            if (builder == null && line.IndexOf("--") != -1)
            {
                var modelName = line.Replace("--", "");
                if (modelName == target)
                {
                    builder = new StringBuilder();
                }
            }
            else if (builder != null)
            {
                if (line.IndexOf("--") == -1)
                {
                    builder.AppendLine(line);
                }
                else
                {
                    break;
                }
            }
        }
        return builder.ToString();
    }

    void ParseAnimFile(string sAnimList, ref System.Collections.ArrayList List)
    {
        Regex regexString = new Regex(" *(?<firstFrame>[0-9]+) *[-_] *(?<lastFrame>[0-9]+) *(?<loop>(loop|noloop| )) *(?<name>[^\r^\n]*[^\r^\n^ ])",
            RegexOptions.Compiled | RegexOptions.ExplicitCapture);

        Match match = regexString.Match(sAnimList, 0);
        while (match.Success)
        {
            ModelImporterClipAnimation clip = new ModelImporterClipAnimation();

            if (match.Groups["firstFrame"].Success)
            {
                clip.firstFrame = System.Convert.ToInt32(match.Groups["firstFrame"].Value, 10);
            }
            if (match.Groups["lastFrame"].Success)
            {
                clip.lastFrame = System.Convert.ToInt32(match.Groups["lastFrame"].Value, 10);
            }
            if (match.Groups["loop"].Success)
            {
                clip.loopTime = match.Groups["loop"].Value == "loop";
            }
            if (match.Groups["name"].Success)
            {
                clip.name = match.Groups["name"].Value;
            }

            List.Add(clip);

            match = regexString.Match(sAnimList, match.Index + match.Length);
        }
    }
}
public class CustomAssetAttribute : Attribute
{

    public string[] extensions; //不同属性对应不同需求，同一需求可能有几种类型文件

    public CustomAssetAttribute(params string[] extention)
    {
        this.extensions = extention;
    }
}
[CustomAsset(".FBX")]
public class m:Editor
{
    private void OnDisable()
    {
        Debug.LogError("123");
    }
    public override void OnInspectorGUI()
    {
        base.OnInspectorGUI();
        GUILayout.Button("123");
    }

}